package org.jingouzhui.domain.strategy.service.rule.chain.factory;

import lombok.*;
import org.jingouzhui.domain.strategy.model.entity.StrategyEntity;
import org.jingouzhui.domain.strategy.repository.IStrategyRepository;
import org.jingouzhui.domain.strategy.service.rule.chain.ILogicChain;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
* @description: 责任链装配工厂
* @author: jingouzhui
* @date: 2025/4/29 13:39
*/
@Service
public class DefaultLogicChainFactory {

    private final Map<String, ILogicChain> logicChainMap;

    private final IStrategyRepository strategyRepository;

    public DefaultLogicChainFactory(IStrategyRepository strategyRepository, Map<String,ILogicChain> logicChainMap) {
        this.logicChainMap = logicChainMap;
        this.strategyRepository = strategyRepository;
    }


    /**
     * 根据策略id组装责任链
     * @param strategyId 策略Id
     * @return 首个责任链
     */
    public ILogicChain openLogicChain(Long strategyId){
        //在strategy中已经配置好了责任链的对应规则
        StrategyEntity strategy = strategyRepository.queryStrategyByStrategyId(strategyId);
        String[] ruleModels = strategy.ruleModels();
        //如果没有配置 走兜底
        if ( ruleModels == null || ruleModels.length == 0) {
            return logicChainMap.get("default");
        }
        ILogicChain headLogicChain = logicChainMap.get(ruleModels[0]);
        ILogicChain currentChain = headLogicChain;
        for (int i = 1; i < ruleModels.length; i++) {
            currentChain = currentChain.appendNext(logicChainMap.get(ruleModels[i]));
        }
        //加入兜底
        currentChain.appendNext(logicChainMap.get("default"));
        return headLogicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /** 抽奖奖品ID - 内部流转使用 */
        private Integer awardId;
        /**  */
        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }
}
